package com.lu.security.tools;

import android.util.Base64;

import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * author: luqihua
 * date:2020/4/3
 * description: 数据转换工具类
 **/
public class HexTools {
    public static String md5(String encryptText) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            digest.update(encryptText.getBytes());
            return byteToHex(digest.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * byte数组转hex
     *
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes, int offset, int len) {
        String strHex;
        StringBuilder sb = new StringBuilder();
        int target = offset + len;
        if (target >= bytes.length) target = bytes.length;
        for (int i = offset; i < target; i++) {
            strHex = Integer.toHexString(bytes[i] & 0xFF);
            if (strHex.length() == 1) {
                sb.append("0");
            }
            sb.append(strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim().toUpperCase();
    }

    /**
     * byte数组转hex
     *
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes) {
        return byteToHex(bytes, 0, bytes.length);
    }

    /**
     * hex转byte数组
     *
     * @param hex
     * @return
     */
    public static byte[] hexToByte(String hex) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i += 2) {
            int result = Integer.parseInt("" + hex.charAt(i) + hex.charAt(i + 1), 16);
            byteBuffer.put((byte) result);
        }
        return byteBuffer.array();
    }

    public static String encodeToBase64(byte[] bytes) {
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    public static byte[] decodeFromBase64(String base64Str) {
        return Base64.decode(base64Str, Base64.NO_WRAP);
    }
}
